<?php

namespace App\Services\Oauth;

use App\Models\Oauth\UserLoginLogModel;
use Illuminate\Support\Facades\Cookie;
use App\Models\Oauth\UserModel;
use App\Models\Oauth\UserTypeMapModel;


class User extends BaseUser
{
    public function __construct(array $user = array())
    {
        if ($user && !empty($user)) {
            //登录的状态
            $this->setLoginStatus($user);
        } else if (!$this->user || !$this->userId) {
            $this->setLoginStatus();
        }
        // $this->setAvatar();
    }

    public function __destruct()
    {
        session()->put($this->getSessionKey(), $this->user);
    }


    /**
     * 设置登录状态
     */
    public function setLoginStatus(array $user = array())
    {
        $sessionUser = session()->get($this->getSessionKey());
        if (!empty($user)) {
            $this->sessionLogin($user);
            //$this->setCookie();
        } else if (isset($sessionUser) && !empty($sessionUser)) {
            $this->user = $sessionUser;
            $this->userId = $this->user['id'];
            //}else if ($this->checkCookie()) {
            // $this->cookieLogin();
        } else {
            $this->loginOut();
        }

    }

    /**
     * 登录成功设置session
     *
     * @param $userArray
     */
    private function sessionLogin(array $userArray)
    {
        //将数组里面的值设置到user对象中
        $this->updateUserInfo($userArray);
        $this->userId = $this->getUserValue('id');
        session()->put($this->getSessionKey(), $this->user);
        UserLoginLogModel::writeLog(UserLoginLogModel::TYPE_LOGIN, $this->userId);
    }

    /**
     * cookie登录
     *
     */
    private function cookieLogin()
    {
        if ($cookie = $this->checkCookie()) {
            $uid = $this->dencodeCookie($cookie);
            if ($uid && $user = UserModel::getUserById($uid)) {
                $this->sessionLogin($user);
            } else {
                Cookie::forget($this->getCookieKey());
            }
        }
    }

    /**
     * 判断帐号是否已经设置了用户类型
     */
    public function isSetUserType($uid)
    {
        $oldUserTypes = UserTypeMapModel::getUserType(array('user_id' => $uid));
        if ($oldUserTypes) {
            //已经设置了用户类型
            return true;
        }
        return false;
    }

}